package com.zztl.infiniteBand

import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Build
import android.os.Environment
import android.os.Handler
import android.support.multidex.MultiDex
import android.support.multidex.MultiDexApplication
import android.view.View
import com.clj.fastble.BleManager
import com.tencent.bugly.Bugly
import com.tencent.bugly.beta.Beta
import com.tencent.bugly.beta.UpgradeInfo
import com.tencent.bugly.beta.ui.UILifecycleListener
import com.zztl.infiniteBand.greendao.DaoMaster
import com.zztl.infiniteBand.greendao.DaoSession
import com.zztl.infiniteBand.service.NLService
import com.zztl.infiniteBand.ui.activity.MainActivity
import com.zztl.infiniteBand.util.language.LanguageUtil
import com.zztl.infiniteBand.util.LogUtils
import com.zztl.infiniteBand.util.language.LanguageManager
import com.zztl.infiniteBand.util.language.LanguageLocalListener
import java.util.*
import com.tencent.bugly.beta.upgrade.UpgradeStateListener
import com.tencent.bugly.beta.upgrade.UpgradeListener
import com.zztl.infiniteBand.ui.activity.UpgradeActivity


/**
 * @desc
 * @auth ${user}
 * @time 2018/9/11  11:58
 */
class BraceletApplication : MultiDexApplication() {


    companion object {
        private val TAG = "BraceletApplication"
        val DB_NAME = "bill2.db"

        lateinit var context: BraceletApplication

        private var mDaoSession: DaoSession? = null

        var watchCountStep: Int = 0


        fun getmDaoSession(): DaoSession? {
            return mDaoSession
        }


        /*     fun getZhBraceletService(): ZhBraceletService? {
                 return zhBraceletService
             }

             fun setZhBraceletService(mzhBraceletService: ZhBraceletService) {

                 zhBraceletService = mzhBraceletService
             }*/

    }

    override fun onCreate() {
        context = this
        initGreenDao()
        BleManager.getInstance().init(this)
        BleManager.getInstance()
                .enableLog(BuildConfig.DEBUG)
                .setReConnectCount(3, 5000)
                .setConnectOverTime(20000).operateTimeout = 5000
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                this.startForegroundService(Intent(this, NLService::class.java))
            } else {
                startService(Intent(this, NLService::class.java))
            }
        } catch (e: Exception) {
        }

        LanguageUtil.init(object : LanguageLocalListener {
            override fun getSetLanguageLocale(context: Context): Locale {
                //返回自己本地保存选择的语言设置
                return LanguageManager.getSetLanguageLocale(context)
            }
        })
        LanguageUtil.setApplicationLanguage(this)
        initBugly()
        super.onCreate()


    }







    override fun attachBaseContext(base: Context?) {
        //第一次进入app时保存系统选择语言(为了选择随系统语言时使用，如果不保存，切换语言后就拿不到了）
        LanguageManager.saveSystemCurrentLanguage(base!!);
        super.attachBaseContext(LanguageUtil.setLocal(base!!))
        if (BuildConfig.ISDEBUG) {
            MultiDex.install(this)
        }
    }


    override fun onConfigurationChanged(newConfig: Configuration?) {
        super.onConfigurationChanged(newConfig)
        //用户在系统设置页面切换语言时保存系统选择语言(为了选择随系统语言时使用，如果不保存，切换语言后就拿不到了）
        LanguageManager.saveSystemCurrentLanguage(applicationContext, newConfig!!)
        LanguageUtil.onConfigurationChanged(applicationContext)

    }


    private fun initGreenDao() {
        val helper = DaoMaster.DevOpenHelper(this, DB_NAME)
        val db = helper.writableDatabase
        val daoMaster = DaoMaster(db)
        mDaoSession = daoMaster.newSession()
    }


    private fun initBugly() {
        Beta.autoInit = true
        Beta.autoCheckUpgrade = false
        /**
         * 设置启动延时为1s（默认延时3s），APP启动1s后初始化SDK，避免影响APP启动速度;
         */
        Beta.initDelay = 1000
        /**
         * 设置通知栏大图标，largeIconId为项目中的图片资源;
         */
        Beta.largeIconId = R.mipmap.ic_launcher
        /**
         * 设置状态栏小图标，smallIconId为项目中的图片资源Id;
         */
        Beta.smallIconId = R.mipmap.ic_launcher
        /*   */
        /**
         * 设置更新弹窗默认展示的banner，defaultBannerId为项目中的图片资源Id;
         * 当后台配置的banner拉取失败时显示此banner，默认不设置则展示“loading“;
         *//*
        Beta.defaultBannerId = R.mipmap.launcher_logo;*/
        /**
         * 设置sd卡的Download为更新资源保存目录;
         * 后续更新资源会保存在此目录，需要在manifest中添加WRITE_EXTERNAL_STORAGE权限;
         */
        Beta.storageDir = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)

        /**
         * 已确认过得弹窗在app下次启动自动检查更新是会再次弹出
         */
        Beta.showInterruptedStrategy = true

        Beta.canShowUpgradeActs.add(MainActivity::class.java)
        //        Beta.tipsDialogLayoutId = R.layout.upgrade_dialog_zh;
//        val language = LanguageManager.getSelectLanguage(this)
//        when(language){
//            getString(com.zztl.infiniteBand.R.string.英语)->{
//                Beta.upgradeDialogLayoutId = R.layout.upgrade_dialog_en
//            }
//            getString(com.zztl.infiniteBand.R.string.简体中文)->{
//                Beta.upgradeDialogLayoutId = R.layout.upgrade_dialog_zh
//            }
//
//        }


        Beta.upgradeListener = UpgradeListener { ret, strategy, isManual, isSilence ->
            if (strategy != null) {
                Handler().postDelayed({
                    val i = Intent()
                    i.setClass(applicationContext, UpgradeActivity::class.java!!)
                    i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    startActivity(i)
                },1000)
            } else {
            }
        }

        /* 设置更新状态回调接口 */
        Beta.upgradeStateListener = object : UpgradeStateListener {
            override fun onUpgradeSuccess(isManual: Boolean) {
            }

            override fun onUpgradeFailed(isManual: Boolean) {
            }

            override fun onUpgrading(isManual: Boolean) {
            }

            override fun onDownloadCompleted(b: Boolean) {

            }

            override fun onUpgradeNoVersion(isManual: Boolean) {
            }
        }

        //   线上目前用的是这个2327151902  974988WshZtt
        Bugly.init(applicationContext, BuildConfig.BUGLYKEY, false)

    }


}
